import Vue from 'vue'
import VueRouter from 'vue-router'
// 引入仓库
import store from "../store"

Vue.use(VueRouter)
// 局部权限拦截
function haveUrl(path, next) {
  // 判断管理员信息中是否含有权限
  let flag = store.getters.getUser.menus_url.find(item => item == path)
  if (flag == undefined) {
    // 没有权限访问则跳转到首页
    next("/home")
  } else {
    // 否则则下一步
    next()
  }
}

const routes = [
  {
    path: '/index',
    component: () => import("../pages/index"),
    // 二级路由
    children: [
      {
        path: "/home",
        component: () => import("../views/home")
      },
      {
        path: "/menu",
        component: () => import("../views/menu/menu"),
        name: "菜单管理",
        // 菜单权限拦截
        beforeEnter: (to, from, next) => {
          haveUrl("/menu", next)
        }
      },
      {
        path: "/role",
        component: () => import("../views/role/role"),
        name: "角色管理",
        // 角色权限拦截
        beforeEnter: (to, from, next) => {
          haveUrl("/menu", next)
        }
      },
      {
        path: "/user",
        component: () => import("../views/user/user"),
        name: "管理员管理",
        // 管理员权限拦截
        beforeEnter: (to, from, next) => {
          haveUrl("/menu", next)
        }
      },
      {
        path: "/cate",
        component: () => import("../views/cate/cate"),
        name: "商品分类",
      },
      {
        path: "/banner",
        component: () => import("../views/banner/banner"),
        name: "轮播图管理",
      },
      {
        path: "/scpecs",
        component: () => import("../views/specsx/specs"),
        name: "商品规格管理",
      },
      {
        path: "/goods",
        component: () => import("../views/goods/goods"),
        name: "商品管理",
      },
      {
        path: "/seck",
        component: () => import("../views/seck/seck"),
        name: "秒杀管理",
      },
      {
        path: "/member",
        component: () => import("../views/member/member"),
        name: "会员管理",
      },
      {
        path: "/map",
        component: () => import("../views/map/map"),
        name: "查看地图",
      },
      // 二级路由重定向
      {
        path: "",
        redirect: "/home"
      }
    ]
  },
  {
    path: '/login',
    component: () => import("../pages/login")
  },
  {
    // 一级路由重定向
    path: '*',
    redirect: "index"
  }
]

const router = new VueRouter({
  mode: 'history',
  base: process.env.BASE_URL,
  routes
})
// 全局登录拦截
router.beforeEach((to, from, next) => {
  // 判断要前往的地址如果为登录则直接next
  if (to.path == "/login") {
    next();
    return
  }
  // 判断是否有管理员信息，有则next
  if (sessionStorage.getItem("userInfo")) {
    next();
    return
  }
  // 未登录状态，访问其他页面则拦截并跳转到登录
  next("login");
})
export default router
